package com.xinyue.ext.reader;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;

import com.xinyue.ext.Label;
import com.xinyue.ext.data.DaoData;
import com.xinyue.ext.data.EntityData;
import com.xinyue.ext.exception.BeanException;
import com.xinyue.ext.exception.ExceptionBase;
import com.xinyue.ext.reader.core.BeanReader;
import com.xinyue.ext.reader.core.DaoReader;
import com.xinyue.ext.util.StringUtil;

public class EntityReader implements Label{
	//异常信息
	private static ExceptionBase exception;
	
	//私有构造器
	private EntityReader() {
	}
	//内部类
	private static class SingletonHolder{
        private static EntityReader instance = new EntityReader();  
    }
	/**
	 * 获得对象实例
	 */
	public static EntityReader getInstance(ExceptionBase exception) {
		EntityReader.exception = exception;
		return SingletonHolder.instance;
	}

	
	/**
	 * 读取一个XML文件中的Entity标签信息，并返回封装对象
	 * @param entity
	 * @param beanPackage
	 * @param daoPackage
	 * @return
	 * @throws Exception
	 */
	public List<EntityData> read(List<Element> entites, String beanPackage, String daoPackage,
			String serPackage, String contPackage) throws Exception {
		
		//读取一个XML文件中的所有Entity标签数据
		List<EntityData> datas = new ArrayList<EntityData>();
		
		for (Element entity: entites) {
			//刷新异常信息对象
			exception.refresh();
			
			//参数集
			ParamHolder holder = new ParamHolder();
			holder.setException(exception);
			holder.setEntity(new EntityData());
			holder.getEntity().setDao(new DaoData());
			
			holder.getEntity().setBeanPackage(beanPackage);
			holder.getEntity().getDao().setDaoPackage(daoPackage);
			holder.getEntity().setSerPackage(serPackage);
			holder.getEntity().setContPackage(contPackage);
			
			/**
			 * 读取entity标签属性
			 */
			String className = entity.attributeValue(name_);
			String table = entity.attributeValue(table_);
			if(StringUtil.isNull(className)) {
				throw new BeanException("entity标签未定义name属性或name属性为空", holder.getException());
			}
			//异常配置信息
			holder.getException().setEntityName(className);
			
			//当table为空时，默认表名和Entity同名
			if(StringUtil.isNull(table)) {
				holder.getEntity().setTable(className.toUpperCase());
			}else {
				holder.getEntity().setTable(table);
			}
			holder.getEntity().setClassName(className);
			
			//是否生成service文件和controller文件
			if("true".equals(entity.attributeValue(service_))) {
				holder.getEntity().setService(true);
			};
			if("true".equals(entity.attributeValue(controller_))) {
				holder.getEntity().setController(true);
			}
			
			/**读取Bean信息*/
			BeanReader beanReader = BeanReader.getInstance(holder);
			beanReader.read(entity);
			/**读取Dao信息*/
			DaoReader daoReader = DaoReader.getInstance(holder);
			daoReader.read(entity);
			
			datas.add(holder.getEntity());
		}
		return datas;
	}
}
